package com.tianji.promotion.service.impl;

import com.tianji.promotion.domain.po.Coupon;
import com.tianji.promotion.domain.po.ExchangeCode;
import com.tianji.promotion.mapper.ExchangeCodeMapper;
import com.tianji.promotion.service.IExchangeCodeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.promotion.utils.CodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;

/**
 * <p>
 * 兑换码 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2023-07-01
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ExchangeCodeServiceImpl extends ServiceImpl<ExchangeCodeMapper, ExchangeCode> implements IExchangeCodeService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    //生成兑换码
    @Async("generateExchangeCodeExecutor")
    @Override
    public void asyncGenerateCode(Coupon localCoupon) {
        // 发放数量
        Integer totalNum = localCoupon.getTotalNum();
        //1. 获取Redis自增序列号
        Long result = redisTemplate.opsForValue().increment("exchange:code:num", totalNum);
        if(result==null){
            return;
        }
        int maxSerialNum=result.intValue();

        ArrayList<ExchangeCode> list = new ArrayList<>(totalNum);
        int startNum=maxSerialNum-totalNum+1;
        for(int i=startNum;i<=maxSerialNum;i++){
            //2. 生成兑换码
            String code = CodeUtil.generateCode(i, localCoupon.getId());
            ExchangeCode e = new ExchangeCode();
            e.setCode(code);
            e.setId(i);//设置ID为兑换码的值，更方便判断兑换码是否零用过
            e.setExchangeTargetId(localCoupon.getId());
            e.setExpiredTime(localCoupon.getIssueEndTime());
            list.add(e);
        }
        //3. 保存数据库
        this.saveBatch(list);
    }
}
